package com.caldremch;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by Caldremch on Mac 2017/2/19 13:11.
 */
public class MybatisTest {

    public static void main(String[] args) {


        Logger logger = Logger.getLogger(MybatisTest.class);

        logger.debug("start");

        //配置文件
        String resource = "SqlMapConfig.xml";

        //得到配置文件流
        try {

            InputStream inputStream = Resources.getResourceAsStream(resource);

            //创建回话工厂, 传入mybatis配置文件信息
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            //得到sqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();

            User user = sqlSession.selectOne("test.findUserById", 1);

            sqlSession.delete("test.deleteUser", 6);
//
            List<User> users = sqlSession.selectList("test.findUserByName", "%"+"小"+"%");

            User user4 = new User();

            user4.id = 1;
            user4.username = "小曾";

            //更新用户
            sqlSession.update("test.updateUser", user4);

//
            System.out.println(user.username);
//
            System.out.println(users.size());

            for (User  user1 :users
                 ) {
                System.out.println(user1.username);
            }

//            插入用户
            User u = new User();

            u.username = "小秦1";
            u.birthday = "2017-4-4";
            u.sex="男";
            u.address="白石洲";

            sqlSession.insert("test.insertUser", u);



            //更新需要提交commit
            sqlSession.commit();

            System.out.println("new insert user ID = "+u.id);

            sqlSession.close();

            logger.debug("end");


        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
